package com.godenwater.recv.server.yf;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class YfClientDataDecoder implements ProtocolDecoder {
	private static final AttributeKey BUF_BYTE = new AttributeKey(
			YfClientDataDecoder.class, "BUF_KEY");

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		try {

			System.out.println(">>> YfClientDataDecoder decode "
					+ StringUtils.trimAllWhitespace(in.getHexDump()));

			IoBuffer buffer = null;
			byte[] buf = (byte[]) session.getAttribute(BUF_BYTE);
			if (buf == null) {
				// System.out.println("没有尚未处理的数据");
				buffer = in;
			} else {
				// System.out.println("合并尚未处理的数据");
				buffer = IoBuffer.allocate(buf.length + in.remaining());
				buffer.setAutoExpand(true);
				buffer.put(buf);
				buffer.put(in);
				buffer.flip();
			}

			// while (buffer.remaining() >= 0) {// 循环处理数据包
			// //
			// int dataLen = buffer.getInt(buffer.position());
			// byte[] b = new byte[dataLen];
			// buffer.get(b);
			// SMPPPacket pak = null;
			// int id = -1;
			// id = SMPPIO.bytesToInt(b, 4, 4);
			// pak = PacketFactory.newInstance(id);
			// if (pak != null) {
			// pak.readFrom(b, 0);
			// out.write(pak);
			// }

			String message = "";

			byte[] mode = new byte[1];
			buffer.get(mode);

			if (mode[0] == (byte)0x24) {
				int len =  buffer.remaining();
				if (len > 0) {// 表示缓冲区中有数据
					// 组装消息
					byte[] body = new byte[len];
					buffer.get(body);
					message = new String(body);
				}
			} else {
				// 处理DTU设备上线时的登录信息，发的是DTU编号和手机号
				// buffer.get(buffer.array().length);
				logger.info(">> 非协议报文 ");
				byte[] remain = new byte[buffer.remaining()];
				buffer.get(remain);
				return ;
			}
			// 组装消息
			out.write(message);

			if (buffer.hasRemaining()) {// 如果有剩余的数据，则放入Session中
				byte[] tmpb = new byte[buffer.remaining()];
				buffer.get(tmpb);
				session.setAttribute(BUF_BYTE, tmpb);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}


	public void dispose(IoSession session) throws Exception {
		// TODO Auto-generated method stub

	}

	public void finishDecode(IoSession session, ProtocolDecoderOutput out)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
